/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gcalscraper;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.ColorProperty;
import com.google.gdata.data.calendar.HiddenProperty;
import com.google.gdata.data.calendar.TimeZoneProperty;
import com.google.gdata.data.extensions.Recurrence;
import com.google.gdata.data.extensions.When;
import com.google.gdata.data.extensions.Where;
import com.google.gdata.util.ServiceException;
import gcalscraper.wapo.Data;
import gcalscraper.wapo.Event;
import gcalscraper.wapo.date.DateParser;
import gcalscraper.wapo.date.Occurrence;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author dave
 */
public class Main {

  public static void main(final String[] args) {
    
    if (args.length < 2) {
      System.out.println("Usage: gcalscraper.Main <google-calendar-username> <google-calendar-password>");
      System.exit(1);
    }
    
    Data d = new Data();
    
    d.load();
    
    output(d, args[0], args[1]);
  }
  
  public static void output(Data d, String userName, String userPassword) {
    final String METAFEED_URL_BASE = "http://www.google.com/calendar/feeds/";
    final String ALLCALENDARS_FEED_URL_SUFFIX = "/allcalendars/full";
    final String OWNCALENDARS_FEED_URL_SUFFIX = "/owncalendars/full";
    final String EVENT_FEED_URL_SUFFIX = "/private/full";


    final String RED = "#A32929";
    final String BLUE = "#2952A3";
    final String GREEN = "#0D7813";
  
    URL metafeedUrl = null;
    URL allcalendarsFeedUrl = null;
    URL owncalendarsFeedUrl = null;
    URL eventFeedUrl = null;

    try {
      
      metafeedUrl = new URL(METAFEED_URL_BASE + userName);
      allcalendarsFeedUrl = new URL(METAFEED_URL_BASE + userName + 
          ALLCALENDARS_FEED_URL_SUFFIX);
      owncalendarsFeedUrl = new URL(METAFEED_URL_BASE + userName + 
          OWNCALENDARS_FEED_URL_SUFFIX);    
      

      // Create CalendarService and authenticate using ClientLogin
      CalendarService service = new CalendarService("rafkind.com-wapo2gcal-0.1");

      service.setUserCredentials(userName, userPassword);      
      
      // Create the calendar
      CalendarEntry calendar = new CalendarEntry();
      calendar.setTitle(
          new PlainTextConstruct(
            "Washington Post City Guide Events"));
      calendar.setSummary(
          new PlainTextConstruct(
            "Scraped from the Washington Post City Guide on " + new Date()));
      calendar.setTimeZone(new TimeZoneProperty("America/New_York"));
      calendar.setHidden(HiddenProperty.FALSE);
      calendar.setColor(new ColorProperty(GREEN));
      calendar.addLocation(new Where("", "", "Washington, DC"));

      calendar = service.insert(owncalendarsFeedUrl, calendar);
      
      String calendarId = calendar.getId().substring(calendar.getId().lastIndexOf("/")+1);
      System.out.println(calendar.getId() + ", " + calendarId);
      
      //System.exit(-1);
      eventFeedUrl = new URL(METAFEED_URL_BASE + calendarId
          + EVENT_FEED_URL_SUFFIX);
      
      DateParser dp = new DateParser();
      
      for (Event e : d.getEvents()) {
        for (Occurrence o : dp.parse(e)) {
          CalendarEventEntry myEntry = new CalendarEventEntry();

          myEntry.setTitle(new PlainTextConstruct(e.getName()));

          /*myEntry.setTitle(
              new HtmlTextConstruct(
                "<a href=\"http://www.washingtonpost.com" + e.getDetailLink() 
                + "\">" + e.getName() + "</a>"
                )
              );*/

          //myEntry.setContent(new PlainTextConstruct(e.getShortDesc()));
          /*myEntry.setContent(
              new HtmlTextConstruct(
                "<u>" + e.getEventType() + "</u> <br>"
                + "<a href=\"http://www.washingtonpost.com" + e.getDetailLink() + "\">" + e.getName() + "</a> <br>"
                + "<p>" + e.getShortDesc() + "</p> <br>"
                + "<i>" + e.getDetailedDateTime() + "</i> <br>"
                + "<a href=\"http://www.washingtonpost.com" + e.getVenueLink() + "\">" + e.getVenue() + "</a> <br>"
                + "<b>" + e.getVenueLocation() + "</b>"
                )
              );*/
          myEntry.setContent(
              new PlainTextConstruct(
                e.getEventType() + "\n\n"
                + e.getName() + "\nhttp://www.washingtonpost.com" + e.getDetailLink() + "\n\n"
                + e.getShortDesc() + "\n"
                + e.getDetailedDateTime() + "\n\n"
                + e.getVenue() + "\n" + e.getVenueLocation() + "\nhttp://www.washingtonpost.com" + e.getVenueLink()
              )
            );

          myEntry.setQuickAdd(false);
          myEntry.setWebContent(null);

          if (o.isRecurrent()) {
            Recurrence recur = new Recurrence();
            recur.setValue(o.recurrenceSpecification());
            myEntry.setRecurrence(recur);
          } else {
            DateTime startTime = new DateTime(
                o.getStart(), 
                TimeZone.getDefault());

            DateTime endTime = new DateTime(
                o.getEnd(), 
                TimeZone.getDefault());

            When eventTimes = new When();
            eventTimes.setStartTime(startTime);
            eventTimes.setEndTime(endTime);
            myEntry.addTime(eventTimes);       
          }
          
          myEntry.addLocation(new Where("", "", e.getVenue()));

          try {
            service.insert(eventFeedUrl, myEntry);
          } catch (IOException ioex) {
            Logger.getAnonymousLogger().log(Level.SEVERE, 
              "Trouble adding " + e.getName() + " @ " + e.getVenue() + "[" 
                + e.getDetailedDateTime() + "] to calendar", ioex);
          } catch (ServiceException sex) {
            Logger.getAnonymousLogger().log(Level.SEVERE, 
              "Trouble adding " + e.getName() + " @ " + e.getVenue() + "[" 
                + e.getDetailedDateTime() + "] to calendar", sex);
          }
        }
      }
    } catch (Exception ex) {
      Logger.getAnonymousLogger().log(Level.SEVERE, 
          "Trouble outputting to calendar", ex);
    }
  }
  
  /**
   * @param args the command line arguments
   */
  public static void mainX(String[] args) {
    Event e = new Event();
    e.setName("test");
    e.setVenue("test");
    e.setDate("1/16");
    /*
     * 8 PM Friday-Saturday, Jan. 18-19
     * 7:30 PM Friday-Saturday, Jan. 18-19
     * 8 and 10 PM Thursday, Jan. 24
     * 8 and 10 PM Wednesday-Saturday, Jan. 16-19
     * 
     * "2-5:15 PM Saturday, Jan. 12

2-5:15 PM Saturday, Jan. 19"
     * 
     * "7 PM Thursday, Jan. 17

1:30 PM Friday, Jan. 18

8 PM Saturday, Jan. 19"
     * 
     * "Dec. 4-Jan. 19:

Opening Reception: 6-9 PM Friday, Dec. 7

11 AM-5 PM Tuesdays-Saturdays"
     * 
     * "11 AM Saturday, Jan. 12

11 AM and 1:30 PM Sunday, Jan. 13

11 AM and 1:30 PM Saturday, Jan. 19"
     * 
     * "Through Jan. 19:

2-6 PM Wednesdays-Fridays

Noon-6 PM Saturdays"
     * 
     * "Nov. 29-Jan. 19:

11 AM-7 PM Wednesdays-Fridays

10 AM-5 PM Saturdays

11 AM-3 PM Sundays

Closed Dec. 22 through Jan. 8"
     * 
     * "Through Jan. 19:

11 AM-6 PM Wednesdays-Saturdays"
     * 
     * "Dec. 15-Jan. 19:

Opening Reception: 7-9 PM Saturday, Dec. 15

1-7 PM Wednesdays-Saturdays"
     * 
     * Wednesday, Jan. 23
     * 
     * "8 and 10 PM Thursday, Jan. 24
     * 
     * 1:30, 4:30 and 7 PM Saturday, Jan. 19

1:30 and 4 PM Sunday, Jan. 20"
     * 
     * "Noon-8 PM Friday, Jan. 18

10 AM-8 PM Saturday, Jan. 19

11 AM-5 PM Sunday, Jan. 20"
     * 
     * 4:30-6 PM Sunday, Jan. 20
     */
    
    e.setDetailedDateTime("8 and 10 PM Thursday, Jan. 24");
    for (Occurrence o : new DateParser().parse(e)) {
      System.out.println(e + "\n" + o);
    }
  }
}
